import React, { useEffect, useState } from 'react';
import { Table, message, Modal, Input, Button, Layout, Menu ,Form} from 'antd';
import 'antd/dist/reset.css';
import { MenuOutlined, SearchOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';

const { Header, Content, Sider } = Layout;


function App() {
  const [natEntries, setNatEntries] = useState([]);

  useEffect(() => {
    fetch('http://localhost:5000/nat_entries')
      .then(response => response.json())
      .then(data => setNatEntries(data));
  }, []);

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '内网 IP', dataIndex: 'internal_ip', key: 'internal_ip' },
    { title: '外网 IP', dataIndex: 'external_ip', key: 'external_ip' },
  ];

  const [form] = Form.useForm();

 // const [total, setTotal] = useState(0);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [editForm] = Form.useForm();
  const [selectedEntry, setSelectedEntry] = useState(null);
  const [searchValues, setSearchValues] = useState({});

  
  const showEditModal = (record) => {
    setSelectedEntry(record);
    editForm.setFieldsValue(record);
    setIsEditModalVisible(true);
  };
  
  const handleEdit = (values) => {
    fetch(`http://localhost:5000/nat_entries/${selectedEntry.id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(values),
    })
     .then(response => response.json())
     .then(data => {
        if (data.message.includes('成功')) {
          message.success(data.message);
          setIsEditModalVisible(false);
          fetchPaginatedNatEntries();
        } else {
          message.error(data.message);
        }
      });
  };
  
  const handleSearch = (values) => {
    setSearchValues(values);
    fetchPaginatedNatEntries();
  };
  
  const fetchPaginatedNatEntries = () => {
    let url = `http://localhost:5000/nat_entries/paginated`;
    if (searchValues.internal_ip) {
      url += `&internal_ip=${searchValues.internal_ip}`;
    }
    if (searchValues.external_ip) {
      url += `&external_ip=${searchValues.external_ip}`;
    }
    fetch(url)
     .then(response => response.json())
     .then(data => {
        setNatEntries(data.data);
       // setTotal(data.total);
      });
  };



  const addNatEntry = (values) => {
    fetch('http://localhost:5000/nat_entries', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(values),
    })
     .then(response => response.json())
     .then(data => {
        if (data.message.includes('successfully')) {
          message.success(data.message);
          form.resetFields();
  
        }
     })
    // 这里可以添加处理表单提交的逻辑
    console.log('表单提交的值:', values);
  };
  const handleDelete = (record) => {
    fetch(`http://localhost:5000/nat_entries/${record.id}`, {
      method: 'DELETE',
    })
     .then(response => response.json())
     .then(data => {
        if (data.message.includes('成功')) {
          message.success(data.message);
          fetch('http://localhost:5000/nat_entries')
           .then(response => response.json())
           .then(data => setNatEntries(data));
        } else {
          message.error(data.message);
        }
      });
  }

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider trigger={null} collapsible collapsed={false}>
        <div className="logo" />
        <Menu theme="dark" mode="inline" defaultSelectedKeys={['1']}>
          <Menu.Item key="1" icon={<MenuOutlined />}>
            NAT 管理
          </Menu.Item>
          <Menu.Item key="2" icon={<MenuOutlined />}>
            NAT 规则
          </Menu.Item>
          <Menu.Item key="3" icon={<MenuOutlined />}>
            网络配置
          </Menu.Item>
          <Menu.Item key="4" icon={<MenuOutlined />}>
            系统设置
          </Menu.Item>
          <Menu.Item key="5" icon={<MenuOutlined />}>
            日志管理
          </Menu.Item>

        </Menu>
      </Sider>
      <Layout className="site-layout">
    
        <Content style={{ margin: '16px 16px' }}>
          <div className="App">
            <h1>NAT 管理系统</h1>

            <Form form={form} onFinish={addNatEntry} layout="inline">
              <Form.Item name="internal_ip" rules={[{ required: true, message: '请输入内网 IP' }]}>
                <Input placeholder="内网 IP" />
              </Form.Item>
              <Form.Item name="external_ip" rules={[{ required: true, message: '请输入外网 IP' }]}>
                <Input placeholder="外网 IP" />
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit">添加</Button>
              </Form.Item>
            </Form>

            <Table
              dataSource={natEntries}
              columns={[
                ...columns,
                { title: '操作', key: 'action', render: (text, record) => (
                  <><Button icon={<EditOutlined />} onClick={() => showEditModal(record)}>
                    编辑
                  </Button><Button icon={<DeleteOutlined />} onClick={() => handleDelete(record)}>
                      删除
                    </Button></>
                )}
              ]}
              rowKey="id"
              pagination={false} // 禁用分页
            />
            <Modal
              title="编辑 NAT 条目"
              open={isEditModalVisible}
              onCancel={() => setIsEditModalVisible(false)}
              footer={null}
            >
              <Form form={editForm} onFinish={handleEdit}>
                <Form.Item name="internal_ip" rules={[{ required: true, message: '请输入内网 IP' }]}>
                  <Input placeholder="内网 IP" />
                </Form.Item>
                <Form.Item name="external_ip" rules={[{ required: true, message: '请输入外网 IP' }]}>
                  <Input placeholder="外网 IP" />
                </Form.Item>
                <Form.Item>
                  <Button type="primary" htmlType="submit">保存</Button>
                </Form.Item>
              </Form>
            </Modal>
          </div>
        </Content>
      </Layout>
    </Layout>
  );
}

export default App;
